package cn.cellcom.agent.struts.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.cellcom.adapter.service.GzhMessageCallback;
import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.hql.TUserHql;
import cn.cellcom.agent.online.client.AgentClient;
import cn.cellcom.agent.online.client.Client;
import cn.cellcom.agent.online.client.ClientManager;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.struts.form.TUserForm;
import cn.cellcom.jar.biz.AbstractBiz;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.pagination.AbstractPaginationBiz;
import cn.cellcom.jar.pagination.IPaginationBiz;
import cn.cellcom.jar.util.BeanUtil;
import cn.cellcom.jar.util.CU;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MD5;
import cn.cellcom.jar.util.MyException;
import cn.cellcom.rpc.entity.KfzhAction;
import cn.cellcom.rpc.entity.KfzhMessage;

public class TUserDpAct extends DispatchAction {

	private IPaginationBiz pbiz;

	private AbstractBiz cbiz;

	private Log log = LogFactory.getLog(this.getClass());

	/**
	 * 查询记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		form = (ActionForm) AbstractPaginationBiz.getPaginationActionForm(req, form);
		List list = null;
		try {
			req.setAttribute("typelist", BeanUtil.startWith("TUser-type"));
			req.setAttribute("statuslist", BeanUtil.startWith("TUser-status"));

			if ("select2".equals(req.getParameter("from"))) {
				pbiz.setPageSize(100);
			}
			log.info("查询的语句：TUserHql()");
			list = pbiz.pagination(mapping, form, req, new TUserHql()).getDataResult();

		} catch (MyException e) {
			return LogUtil.e(this.clazz, "操作出现错误", e, mapping, req);
		}
		String from = req.getParameter("from");
		if ("select2".equals(from) || "select2-2".equals(from)) {
			LogonSession ls = new LogonSession(req);
			TUser self = (TUser) ls.getLogonObject();
			List<Map<String, String>> mlist = new ArrayList<Map<String, String>>();
			for (int i = 0; i < list.size(); i++) {
				TUser user = (TUser) list.get(i);
				// 不查询自己--->20180225：select2-2表示邀请、转接时候选择坐席，不出现自己
				if ("select2-2".equals(from) && user.getUsername().equals(self.getUsername())) {
					continue;
				}
				Map<String, String> e = new HashMap<String, String>();
				e.put("id", user.getUsername());
				Client client = ClientManager.getInstance().getClient(user.getUsername());
				if (StringUtils.equals(req.getParameter("onlyOnline"), "checked") && client == null) {
					continue;
				}
				String rate = "";
				if (client != null) {
					AgentClient ac = (AgentClient) client;
					rate = "[" + ac.getAgentConfig().getCurrentChat() + "/" + ac.getAgentConfig().getMaxChat() + "]";
				}
				e.put("text", user.getName() + "[" + (client == null ? "不在线" : "在线") + "]" + rate);
				mlist.add(e);
			}
			Response.succ(rep, mlist);
			return null;
		}
		req.setAttribute(Env.DATA_NAME, list);
		return mapping.findForward("list");
	}

	/**
	 * 准备记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		req.setAttribute("typelist", BeanUtil.startWith("TUser-type"));
		req.setAttribute("statuslist", BeanUtil.startWith("TUser-status"));

		return mapping.findForward("add");
	}

	/**
	 * 执行记录添加
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TUserForm fm = (TUserForm) form;
		Object obj = null;
		try {
			obj = cbiz.add(req, fm, null);
		} catch (MyException e) {
			LogUtil.e(this.clazz, "新增数据出现异常", e);
		}
		log.info("新增记录结果：" + obj);
		String message;
		if (obj == null || !(obj instanceof TUser)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		} else {
			TUser user = (TUser) obj;
			if(AgentConstant.YES.equals(user.getStatus())) {
				KfzhMessage kf = new KfzhMessage();
				kf.setKfAccount(user.getUsername());
				kf.setAction(KfzhAction.ADD);
				kf.setNickname(CU.getFirstNotNull(user.getNickName(), user.getName()));
				kf.setPassword(user.getPassword());
				GzhMessageCallback.getInstance().kfzh(kf, "");
			}

			message = "记录添加成功";
		}

		add(mapping, fm, req, rep);
		// req.setAttribute("success", fm);
		req.setAttribute(Env.DATA_NAME, message);
		return mapping.findForward("add");
	}

	/**
	 * 准备修改记录
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TUserForm fm = (TUserForm) form;
		try {
			java.lang.String key = fm.getId();
			TUser rf = (TUser) cbiz.getDao().myGet(TUser.class, key);
			if (rf == null) {
				req.setAttribute(Env.DATA_NAME, "读取数据错误");
				return mapping.findForward("error");
			}
			req.setAttribute(Env.DATA_NAME, rf);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "读取数据错误", e, mapping, req);
		}
		req.setAttribute("typelist", BeanUtil.startWith("TUser-type"));
		req.setAttribute("statuslist", BeanUtil.startWith("TUser-status"));
		return mapping.findForward("modify");
	}

	/**
	 * 执行记录修改
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doModify(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		TUserForm fm = (TUserForm) form;
		TUser old = null;
		try {
			old = (TUser) cbiz.getDao().myGet(TUser.class, fm.getUsername());
		} catch (MyException e1) {
		}
		
		Object obj = null;
		try {
			obj = cbiz.modify(req, fm, null);
		} catch (MyException e) {
			LogUtil.e(this.clazz, "修改数据出现异常", e);
		}
		log.info("修改记录结果：" + obj);
		if (obj == null || !(obj instanceof TUser)) {
			req.setAttribute(Env.DATA_NAME, "操作失败，" + obj);
			return mapping.findForward("error");
		} else {
			TUser user = (TUser) obj;
			KfzhMessage kf = new KfzhMessage();
			if(AgentConstant.YES.equals(old.getStatus()) && AgentConstant.YES.equals(user.getStatus())) {
				kf.setAction(KfzhAction.UPDATE);
			} else if(AgentConstant.YES.equals(old.getStatus()) && AgentConstant.NO.equals(user.getStatus())) {
				kf.setAction(KfzhAction.DELETE);
			} else if(AgentConstant.NO.equals(old.getStatus()) && AgentConstant.YES.equals(user.getStatus())) {
				kf.setAction(KfzhAction.ADD);
			} else {//修改前后都是无效状态，那么不需要调用接口
				kf = null;
			}
			if(kf != null) {
				kf.setKfAccount(user.getNo() + "@wxb3281bf4dcf57e4f");
				kf.setNickname(CU.getFirstNotNull(user.getNickName(), user.getName()));
				kf.setPassword(MD5.toMd5(user.getPassword()));
				GzhMessageCallback.getInstance().kfzh(kf, "");
			}
		}
		req.setAttribute(Env.DATA_NAME, "记录修改成功");
		return mapping.findForward("success");
	}

	public void setCbiz(AbstractBiz cbiz) {
		this.cbiz = cbiz;
	}

	public void setPbiz(IPaginationBiz pbiz) {
		this.pbiz = pbiz;
	}
}
